//https://leetcode.cn/problems/target-sum/
package codeRandomThoughts.Test494目标和;

public class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        //推出来的公式
        //正集和 = (sum + target)/2
        if ((sum + target) % 2 == 1) return 0;//此时构造不了表达式
        if (Math.abs(target) > sum) return 0;//全部都一个符号也构造不了

        //我们要在集合中找和为positiveSum的组合
        int positiveSum = (sum + target) / 2;

        //0~i个数字填满容积为j的包,有j种方法
        int[] dp = new int[positiveSum + 1];

        //初始化
        dp[0] = 1;

        for (int i = 0; i < nums.length; i++) {
            for (int j = positiveSum; j >= nums[i]; j--) {
                dp[j] += dp[j - nums[i]];
            }
        }

        return dp[positiveSum];
    }
}
